package com.uniriho.lxr0860_printer.print;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.uniriho.lxr0860_printer.App;
import com.uniriho.lxr0860_printer.AppCacheUtils;
import com.uniriho.lxr0860_printer.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class PrintActivity extends AppCompatActivity {




    Context mContext;

    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.CHINA);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_print);
        mContext = this;
        checkAndRequestPermissions();


        findViewById(R.id.btnCreatePrint).setOnClickListener(v -> {
            createPrint();
        });
        findViewById(R.id.btnPrintExistPDF).setOnClickListener(v -> {
            printExistPdf();
        });
        findViewById(R.id.btnPrintForm).setOnClickListener(v -> {
            formPrint();
        });
        findViewById(R.id.btnPrintImg).setOnClickListener(v -> {
            Intent i = new Intent(this, ImageViewActivity.class);
            startActivity(i);
        });
        findViewById(R.id.btnCreateForm).setOnClickListener(v -> {
            Intent form = new Intent(this, TemplateActivity.class);
            startActivity(form);
        });

    }

    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
            }else {
                AppCacheUtils.getCacheRootFile();
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 || requestCode ==101) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限授予
                AppCacheUtils.getCacheRootFile();
            } else {
                // 权限被拒绝
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void formPrint() {
        String state = AppCacheUtils.getFile("state.pdf").getAbsolutePath();
        String state_src = AppCacheUtils.getFile("state_src.pdf").getAbsolutePath() ;
        String state_dest = AppCacheUtils.getFile("state_dest.pdf").getAbsolutePath() ;
        File src = new File(state_src);
        File dest = new File(state_dest);
        if (src.exists())
            src.delete();

        if (dest.exists()) {
            dest.delete();
        }
        PdfReader reader = null;
        try {
            reader = new PdfReader(state);
            PdfStamper stamper = new PdfStamper(reader,
                    new FileOutputStream(state_src));
            AcroFields fields = stamper.getAcroFields();
            fields.setField("name", "CALIFORNIA");
            fields.setField("abbr", "CA");
            fields.setField("capital", "Sacramento");
            fields.setField("city", "Los Angeles");
            fields.setField("population", "36,961,664");
            fields.setField("surface", "163,707");
            fields.setField("timezone1", "PT (UTC-8)");
            fields.setField("timezone2", "-");
            fields.setField("dst", "YES");
            stamper.close();
            reader.close();

            PdfUtil.write(state_src, dest);
            PdfUtil.print(state_dest);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    private void printExistPdf() {

//        File dest = AppCacheUtils.getFile("test2.pdf");
//        if (dest.exists()) {
//            dest.delete();
//        }
//        PdfUtil.write(AppCacheUtils.getFile("test.pdf").getAbsolutePath(),dest);
//        PdfUtil.print(dest.getAbsolutePath());
        Log.i("zsm", "device 打印");
//                sendCpcl();
//                usbPrinter.write("hello word!!!".getBytes());
//                startActivityForResult( new Intent(PrinterTest.this, UsbDeviceList.class ), Constant.USB_REQUEST_CODE );
        File doc= AppCacheUtils.getFile("test2.pdf");
        Log.i("zsm","path:"+doc.getAbsolutePath());
//              ComponentName comp = new ComponentName("com.dynamixsoftware.printershare","com.dynamixsoftware.printershare.ActivityPrintPDF");
        ComponentName comp = new ComponentName("com.dynamixsoftware.printershare","com.dynamixsoftware.printershare.ActivityPrintDocuments");
        Intent intent = new Intent();
        intent.setComponent(comp);
        intent.setAction("android.intent.action.VIEW");
        intent.setType("application/pdf");
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(PrintActivity.this, "com.uniriho.lxr0860_printer.FileProvider", doc);
        } else {
            uri = Uri.fromFile(doc);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        Log.i("zsm","uri:"+uri);
//        uri= Uri.parse(Uri.decode("content://com.uniriho.lxr0860_printer.provider/test_dest.pdf"));
        intent.setData(uri);
        startActivity(intent);
    }

    /**
     * 创建PDF文档并打印
     */
    public void createPrint() {

        Document document = new Document();//创建文档对象
        PdfWriter writer = null;
        File src = AppCacheUtils.getFile("pdf","create_src.pdf");
        File dest = AppCacheUtils.getFile("pdf","create_dest.pdf");

        try {
            writer = PdfWriter.getInstance(document, new FileOutputStream(src));
            writer.setPdfVersion(PdfWriter.VERSION_1_7);
            document.open();
            Font font = FontFactory.getFont(PdfUtil.FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            document.add(new Paragraph("创建PDF文档并打印！", font));
            document.add(new Paragraph("生成时间：" + mSimpleDateFormat.format(new Date(System.currentTimeMillis())), font));

            document.close();
            PdfUtil.write(src.getAbsolutePath(), dest);
            PdfUtil.print(dest.getAbsolutePath());

        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }


}
